package com.crazy.practice.boot.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author panyonghui
 * @describe 连接配置
 * @date 2022/1/17 10:08
 */
@Configuration
public class ConnectConfig {

    public static final String HTTP_11_NIO_PROTOCOL = "org.apache.coyote.http11.Http11NioProtocol";
    /**
     * SSL链接端口号
     */
    @Value("${server.port}")
    private int serverPort;

    /**
     * 非安全链接端口号
     */
    @Value("${server.unsafe.port}")
    private int serverUnsafePort;

    /**
     * http协议是否允许访问，false将重定向到安全链接
     */
    @Value("${server.unsafe.secure}")
    private boolean serverSecure;

    /**
     * 非安全链接协议（http）
     */
    @Value("server.unsafe.agreement")
    private String serverUnsafeAgreement;

    /**
     * @describe 设置Connector对象的属性
     * @auther crazy_cat
     * @date 2022/1/17 10:55
     * @param
     * @return org.apache.catalina.connector.Connector
     * @modify
     */
    @Bean
    public Connector connector(){
        Connector connector = new Connector(HTTP_11_NIO_PROTOCOL);
        // http协议
        connector.setScheme(serverUnsafeAgreement);
        // http协议的端口号
        connector.setPort(serverUnsafePort);
        // http协议是否允许访问，false将重定向到安全链接
        connector.setSecure(serverSecure);
        // 重定向ssl端口号
        connector.setRedirectPort(serverPort);
        return connector;
    }

    /**
     * @describe 把不安全的http重定向到安全的https链接
     * @auther crazy_cat
     * @date 2022/1/17 10:54
     * @param connector
     * @return org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory
     * @modify
     */
    @Bean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector){
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(){
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(connector);
        return tomcat;
    }
}
